﻿using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace Alex.DataLibrary.Tables
{
    [XmlRoot("TablesDictionary")]
    public class TablesDictionary : Dictionary<string, DataTableStandart>, IXmlSerializable
    {
        public TablesDictionary() : base()
        {
        }

        public void WriteXml(XmlWriter writer)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(string));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(DataTableStandart));
            foreach (KeyValuePair<string, DataTableStandart> pair in this)
            {
                writer.WriteStartElement("Element");
                writer.WriteStartElement("NameTable");
                keySerializer.Serialize(writer, pair.Key);
                writer.WriteEndElement();
                writer.WriteStartElement("Table");
                valueSerializer.Serialize(writer, pair.Value);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }

        public void ReadXml(XmlReader reader)
        {
            XmlSerializer keyDeserializer = new XmlSerializer(typeof(string));
            XmlSerializer valueDeserializer = new XmlSerializer(typeof(DataTableStandart));
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.EndElement &&
                    reader.Name == "Element")
                {
                    reader.Read();
                }
                if (reader.NodeType == XmlNodeType.EndElement &&
                    reader.Name == "TablesDictionary")
                {
                    break;
                }
                if (reader.Name != "Element")
                {
                    throw new XmlException("Invalid XML");
                }
                reader.Read();
                if (reader.Name != "NameTable")
                {
                    throw new XmlException("Invalid XML");
                }
                reader.Read();
                string key = (string)keyDeserializer.Deserialize(reader);
                reader.Read();
                if (reader.Name != "Table")
                {
                    throw new XmlException("Invalid XML");
                }
                reader.Read();
                DataTableStandart value = (DataTableStandart)valueDeserializer.Deserialize(reader);
                this.Add(key, value);
            }
        }

        public XmlSchema GetSchema()
        {
            return (null);
        }

    }
}
